package com.banmoon.wait;

/**
 * 虚假唤醒，问题演示
 */
public class Demo4 {

    public static void main(String[] args) {
        MyDemo4 myDemo4 = new MyDemo4();
        new Thread(() -> {
            for(int i = 0; i < 10; i++) myDemo4.increment();
        }, "线程A").start();
        new Thread(() -> {
            for(int i = 0; i < 10; i++) myDemo4.decrement();
        }, "线程B").start();
        new Thread(() -> {
            for(int i = 0; i < 10; i++) myDemo4.increment();
        }, "线程C").start();
        new Thread(() -> {
            for(int i = 0; i < 10; i++) myDemo4.decrement();
        }, "线程D").start();

    }

}

class MyDemo4{

    private int number = 0;

    public synchronized void increment(){
        try {
            while (number==1)
                wait();
            number++;
            System.out.println(Thread.currentThread().getName() + "：" + number);
            notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void decrement(){
        try {
            while (number==0)
                wait();
            number--;
            System.out.println(Thread.currentThread().getName() + "：" + number);
            notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}